const fs=require('fs');
const path=require('path');
const request=require('request-promise');
const {spawn}=require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function init(){
    if (fs.existsSync('./chong.ts'))
    {
        fs.unlinkSync('./chong.ts');
    }

    if (fs.existsSync('./tmp.m3u8'))
    {
        fs.unlinkSync('./tmp.m3u8');
    }

    let mutxt=fs.readFileSync('./m3u8.txt','utf-8');
    let txtArr=mutxt.split('\r\n');
    let index=0;
    
    let klist=[];
    let kindex=0;
    for (let item of txtArr){
        if (item.indexOf('#EXT-X-DISCONTINUITY')!==-1){
            continue;
        }

        if (item.substring(0,7)==='http://'){
            klist.push(item);
            item=`${__dirname}\\tmp${kindex}.ts`;
            kindex++;
        }

        item+=`\r\n`;
        fs.writeFileSync(`./tmp.m3u8`,item,{
            flag:'a',
            encoding:'utf-8'
        })

        
    }

    // process.exit();
    console.log(`共${klist.length}块`);
    
    for (let item of klist){
        let buf=await request({
            url:item,
            encoding:null
        }).catch((e)=>{
            console.log(e);
        })
        
        fs.writeFileSync(`./tmp${index}.ts`,buf,{
            flag:'a'
        })
        index++;
        console.log(`下载${index}块`);
    }

    console.log('ffmpeg合并');
    
    let margeTT=spawn('ffmpeg',['-i','tmp.m3u8','-c','copy','chong.ts']);
    margeTT.stdout.on('data', function (data) {
      console.log('stdout: \r\n' + data);
    });
  
    margeTT.stderr.on('data', function (data) {
      console.log('stderr: \r\n' + data);
    });
  
    margeTT.on('exit', function (code) {
        console.log('程序退出' + code);
        
        for (let i=0;i<klist.length;i++){
            fs.unlinkSync(`./tmp${i}.ts`);
        }
        fs.unlinkSync(`./tmp.m3u8`);
    });

    
    
}



init();
